package com.atguigu.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    private int num=50;
//    public synchronized void sale(){
//        if(num>0){
//            System.out.println(Thread.currentThread().getName()+"卖出品:"+(num--)+"还剩下:"+num);
//        }
//    }

    private final Lock lock = new ReentrantLock();//Renntrantlock 叫可重复锁+悲观默认锁+默认非公平锁
    public void sale(){
        lock.lock();
        try{
            if(num>0){
                System.out.println(Thread.currentThread().getName()+"卖出品:"+(num--)+"还剩下:"+num);
            }
        }finally {
            lock.unlock();
        }
    }
}
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
//        //V1
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i < 50; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "a").start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i < 50; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "b").start();
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                for (int i = 0; i < 50; i++) {
//                    ticket.sale();
//                }
//            }
//        }, "c").start();

            //V2
        new Thread(() ->{for(int i=1;i<=50;i++){ticket.sale();}},"a").start();
        new Thread(() ->{for(int i=1;i<=50;i++){ticket.sale();}},"b").start();
        new Thread(() ->{for(int i=1;i<=50;i++){ticket.sale();}},"c").start();
    }

}
